package org.threebitsoftware.tbb.dao.bridge;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.threebitsoftware.dao.generated.ContactKey;
import org.threebitsoftware.dao.generated.Emailaddress;
import org.threebitsoftware.dao.generated.EmailaddressKey;
import org.threebitsoftware.dao.generated.dao.EmailaddressDAO;
import org.threebitsoftware.dao.generated.orm.ContactDAOImpl;
import org.threebitsoftware.dao.generated.orm.EmailaddressDAOImpl;
import org.threebitsoftware.tbb.dao.Contact;
import org.threebitsoftware.tbb.dao.DaoHelper;
import org.threebitsoftware.tbb.dao.EmailAddress;

import com.pew.util.dao.DatabaseUtil;

/*
 * Created: Nov 14, 2009
 * Original Author: Elwin
 * Project:
 * Copyright:
 * 
 * Purpose:
 */

/*
 * Copyright (c) 2009, 3BitSoftware
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the <organization> nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

public class EmailAddressBridge {
	private static Logger cLogger = Logger.getLogger(EmailAddressBridge.class);
	
	public static void storeEmailAddress(EmailAddress myObject)
	{
		EmailaddressDAOImpl lDAO = new EmailaddressDAOImpl();
		
		try {
		
			if(myObject.isMarkedForDeletion())
			{
				cLogger.debug("Found delete for: " + myObject.toString());
				if(myObject.getIdContact() > -1)
				{
					EmailaddressKey lKey = new EmailaddressKey();
					lKey.setIdAppUser(new Integer(myObject.getIdAppUser()).longValue());
					lKey.setSEmail(myObject.getEmailAddress());
					lDAO.delete(lKey, DaoHelper.getDBConnection());
				}
				else
				{
					cLogger.info("Nothting to do for Contact:" + myObject.toString() + "; it is not in the database based; decesion on no ID.");
				}
			}
			else
			{
				create(lDAO, myObject);
			}
		}
		catch(SQLException sqlex)
		{
			cLogger.error("An exception occured while trying to perform an operation to: " + myObject.toString());
			cLogger.error(sqlex.toString());
		}
	}
	
	/**
	 * Stores multiple objects into the storage medium.
	 * @param myContact ; An array of objects.
	 */
	public static void storeContact(EmailAddress myObject[])
	{
		cLogger.debug("Entered storeContact(myContact[])");
		
		int liSize = myObject.length;
		for(int i = 0; i < liSize; i++) {
			storeEmailAddress(myObject[i]);
		}
		
		cLogger.info("Worked on storing " + liSize + " phone numbers.");
		
	}
	
	/**
	 * Retrieves an object based on the unique
	 * id passed into it.
	 * @param myId ; A unique identifier for a Contact
	 * @return A Contact object; null if none exists or an error occurs.
	 */
	public static EmailAddress getEmailAddress(String myId, int myAppId)
	{
		EmailAddress lDomainObject = null;
		Emailaddress lDaoObject = null;
		
		cLogger.debug("Getting a DAO object for id: " + myId);
		
		EmailaddressDAOImpl lDAO = new EmailaddressDAOImpl();
		EmailaddressKey lKey = new EmailaddressKey();
		lKey.setSEmail(myId);
		lKey.setIdAppUser((new Integer(myAppId)).longValue());
		
		try {
			lDaoObject = lDAO.load(lKey, DaoHelper.getDBConnection());
		}
		catch(SQLException sqlex)
		{
			cLogger.error("Error retrieving phone number with id:" + myId, sqlex);
		}
		
		lDomainObject = mapDaoToDomain(lDaoObject);
		
		return lDomainObject;
	}
	
	
	/**
	 * Retrieves multiple objects based on a 
	 * SQL-92 based conditional clause.
	 * @return An array of Contact objects; null if an error occurs.
	 */
	public static EmailAddress[] getEmailAddresses(String myQuery, int myAppId)
	{
		cLogger.debug("Attempting to gather multiple domain objects based" +
				" on id query: " + myQuery + " and app user id" + myAppId);
		
		ArrayList<EmailAddress> lDomainListColl = new ArrayList<EmailAddress>();
		EmailAddress lDomainList[] = null;
		ResultSet lRS = null;
		
		lRS = DatabaseUtil.runSelectStatement(DaoHelper.getDBConnection(),
				"SELECT ID_APP_USER, S_EMAIL FROM EMAILADDRESS WHERE " + myQuery 
				+ " AND ID_APP_USER = " + myAppId);
		int lTempId =  -1;
		String lTempString = null;
		int i = 0;
		
		try {
			cLogger.debug("The query returned:" + lRS.getFetchSize());
			//lDomainList = new EmailAddress[lRS.getFetchSize()];
			
			while(lRS.next()) {
				lTempId = lRS.getInt(1);
				lTempString = lRS.getString(2);
				lDomainListColl.add(getEmailAddress(lTempString, lTempId));
			}
		}
		catch (SQLException sqlex)
		{
			cLogger.error("Exception occured while getting contacts based on"
					+ " query: " + myQuery, sqlex);
		}
		
		// temp testing the .getFetchSize() seems to not return ResultSet size
		lDomainList = new EmailAddress[lDomainListColl.size()];
		int countEmail = 0;
		for(EmailAddress email : lDomainListColl) {
			lDomainList[countEmail] = email;
			countEmail++;
		}

		return lDomainList;
	}
	
	
	/**
	 * Maps the dao object to the domain object.
	 * @param myDaoObject
	 * @return A filled domain object; null if failure.
	 */
	public static EmailAddress mapDaoToDomain(Emailaddress myDaoObject) {
		cLogger.debug("Attempting to map a dao to a domain object.");
		
		EmailAddress lDomain = null;
		if(myDaoObject != null)
		{
			lDomain = new EmailAddress(
					myDaoObject.getSEmail(), myDaoObject.getSDescription());
			lDomain.setIdAppUser((new Long(myDaoObject.getIdAppUser())).intValue());
			lDomain.setIdContact((new Long(myDaoObject.getIdContact())).intValue());
			
			cLogger.debug("Filled with: " + lDomain.toString());
		}
		else if(cLogger.isDebugEnabled())
		{
			cLogger.debug("No DAO object to be mapped.");
		}
		
		return lDomain;
	}
	
	/**
	 * Maps the domain object 
	 * @param myDomainObject
	 * @return
	 */
	public static Emailaddress mapDomainToDao(EmailAddress myDomainObject) {
		
		cLogger.debug("Attempting to map a Domain object to a dao object");
		
		Emailaddress lDaoObject = null;
		
		if(myDomainObject != null )
		{
			lDaoObject = new Emailaddress();
			lDaoObject.setIdAppUser((new Integer(myDomainObject.getIdAppUser())).longValue());
			lDaoObject.setIdContact((new Integer(myDomainObject.getIdContact())).longValue());
			lDaoObject.setSDescription(myDomainObject.getDescription());
			lDaoObject.setSEmail(myDomainObject.getEmailAddress());
			
			cLogger.debug("Done filling.  Filled with: " + lDaoObject.toString());
		}
		else if(cLogger.isDebugEnabled())
		{
			cLogger.debug("Nothing to map.");
		}
		
		cLogger.debug("Done with filling a dao object.");
		return lDaoObject;
	}
	
	/**
	 * Create or updates an object.
	 * @param myDAO T
	 * @param myObject
	 */
	static void create(EmailaddressDAO myDAO, EmailAddress myObject)
	{
		Emailaddress lDaoObject = mapDomainToDao(myObject);
		String lClassName = myObject.getClass().getName();
		
		cLogger.debug("Attempting to create / update a " + lClassName);
		
		try {
			//See if it already exists.
			if(emailAddressExists(myObject))
			{
				// perform an update
				cLogger.debug("Email address found, attempting to update.");
				myDAO.update(lDaoObject, DaoHelper.getDBConnection());
			}
			else
			{
				//perform a create
				cLogger.debug("Email address not found, creating a new one.");
				myDAO.create(lDaoObject, DaoHelper.getDBConnection());
			}
		}
		catch(SQLException sqlex)
		{
			cLogger.error("SQL Exception occurred while either updating or creating an object", sqlex);
		}
		
		cLogger.debug("Done creating or editing an object");
	}
	
	/**
	 * Returns if an e-mail address exists allready or not.
	 * @param myObject
	 * @return
	 */
	public static boolean emailAddressExists(EmailAddress myObject)
	{
		boolean lbExists = false;
		
		EmailaddressDAO lDAO = new EmailaddressDAOImpl();
		EmailaddressKey lKey = new EmailaddressKey();
		lKey.setIdAppUser((new Integer(myObject.getIdAppUser())).longValue());
		lKey.setSEmail(myObject.getEmailAddress());
		
		try {
			if(lDAO.load(lKey, DaoHelper.getDBConnection()) == null)
			{
				cLogger.debug("Email does not exist");
				lbExists = false;
			}
			else
			{
				cLogger.debug("Email exists.");
				lbExists = true;
			}
		}
		catch(SQLException sqlex)
		{
			cLogger.error("SQL Exception thrown while testing for an email address",
					sqlex);
		}
		
		return lbExists;
	}

}
